<template>
  <div class="content-detail">
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>基础信息</span>
          <div v-if="show1" @click="show1 = !show1" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show1 = !show1" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <flow-basic-info :basicInfoData="formBaseInfo" v-show="show1" />
      </el-collapse-transition>
    </el-card>

    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>流程状态</span>
          <div v-if="show4" @click="show4 = !show4" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show4 = !show4" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <status-info
          :currentStep="currentStep"
          :steps="steps"
          :isChargehand="isChargehand"
          jumpStep="副厂长"
          v-show="show4"
        />
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box" v-if="isEdit">
      <template #header>
        <div class="card-box-header">
          <span>待处理</span>

          <div v-if="show5" @click="show5 = !show5" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show5 = !show5" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>

      <div v-show="show5" class="content-box">
        <el-form
          ref="flowFormRef"
          :model="flowFormData"
          :rules="fromRules"
          label-width="140px"
          class="form__content"
        >
          <el-form-item label="整改照片" prop="defaultFileList">
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :accept="acceptTypes"
              name="uploadFile"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :on-error="handleError"
              :on-preview="handlePreview"
              multiple
              :file-list="flowFormData.defaultFileList"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <template #tip>
                <div class="el-upload__tip">
                  支持上传doc、docx、xls、xlsx、pdf、png、jpg、jpeg等格式文件,文件大小不得大于20M。
                </div>
              </template> -->
            </el-upload>
          </el-form-item>

          <el-form-item label="整改信息" prop="approvalComments" v-if="isEdit">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="flowFormData.approvalComments"
            ></el-input>
          </el-form-item>
        </el-form>

        <div class="form__footer right-align-box" v-if="isEdit">
          <el-button type="primary" @click="handleSubmit">提 交</el-button>
          <el-button
            v-if="nodeDefId !== 'ACT_010'"
            type="primary"
            @click="handleReject"
            >驳 回</el-button
          >
        </div>
      </div>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>流转记录</span>
          <div v-if="show6" @click="show6 = !show6" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show6 = !show6" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <flow-info
          v-show="show6"
          :instanceId="instanceIdFlow"
          :nodeDefId="nodeDefId"
        />
      </el-collapse-transition>
    </el-card>
    <el-dialog
      title="选择人员"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        :isSingle="true"
        @emitAddUser="showNextJump"
      />
    </el-dialog>
    <el-dialog
      title="驳回"
      v-model="dialogVisible"
      destroy-on-close
      width="600px"
    >
      <reject-view v-model:dialogVisible="dialogVisible" :taskId="taskIdMain" />
    </el-dialog>

    <el-dialog
      title="下一步流转至"
      v-model="dialogVisibleNext"
      destroy-on-close
      width="600px"
    >
      <div class="next-content">
        <el-radio-group
          v-if="nextJumpToArr && nextJumpToArr.length"
          v-model="nextJumpToId"
        >
          <el-radio
            v-for="item in nextJumpToArr"
            :key="item.id"
            :label="item.id"
            border
            @change="changeNextJump"
            >{{ item.name }}</el-radio
          >
        </el-radio-group>
      </div>

      <div class="form__footer">
        <el-button @click="dialogVisibleNext = false">取 消</el-button>
        <el-button type="primary" @click="handleNextJump">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ProcessStatusEnum } from "../types";
import NotifMessage from "/@/utils/message/notification";
import StatusInfo from "/@/views/approval/components/processInfo/StatusInfo.vue";
import FlowInfo from "/@/views/approval/components/processInfo/FlowInfo.vue";
import FlowBasicInfo from "../components/flowBasicInfo.vue";
import AddUser from "/@/views/projectsA/acceptance/concealed/components/dialog/AddUser.vue";
import RejectView from "../components/rejectView.vue";
import {
  acceptTypes,
  uploadUrl,
  handlePreview,
  handleError,
  beforeAvatarUpload
} from "/@/utils/file";
import { storageLocal } from "/@/utils/storage";
import { checkRecordInfo, flowSubmit } from "/@/api/construction";
import { flowTypeObj } from "./type";

const props = defineProps({
  instanceId: {
    type: Number,
    default: 0
  },
  flowId: {
    type: Number || String,
    default: ""
  },
  flowType: {
    type: Number || String,
    default: "1015"
  },
  taskId: {
    type: Number || String,
    default: ""
  },
  contractId: {
    type: Number,
    required: true,
    default: 0
  },
  nodeDefId: {
    type: String,
    required: true,
    default: "ACT_010"
  },
  isEdit: {
    type: Boolean,
    required: true,
    default: false
  }
});
const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};
const router = useRouter();
let currentStep = ref(ProcessStatusEnum.ACT_010);
const flowFormRef = ref<HTMLFormElement | null>(null) as any;
let currentNode = ref("");
let steps = ref([]);
let nextJumpToArr = ref([]);
let nextJumpToId = ref("");
let formBaseInfo = ref<object>({}); // 基础信息
let addUserInfo = ref<object>({}); // 人员选择器，所选择人员信息
let flowFormData = ref({
  approvalComments: "",
  defaultFileList: []
}); // 待处理信息
let dialogVisibleTransferAdd = ref(false); // 选择人员的弹窗是否显示
let dialogVisibleType = ref("submit");
let dialogVisible = ref(false); // 驳回弹窗是否展示
let dialogVisibleNext = ref(false);
let acceptUsers = ref([]); // 已选择人员
let instanceIdFlow = ref(); // 实例ID
let flowType = ref(props.flowType);
let taskIdMain = ref("");
let show1 = ref(true);
let show4 = ref(true);
let show5 = ref(true);
let show6 = ref(true);
// let defaultFileList = ref([]);
let isChargehand = ref("0");
const fromRules = ref({
  approvalComments: [
    { required: true, message: "请输入整改信息", trigger: "change" }
  ],
  defaultFileList: [
    { required: true, message: "请上传照片", trigger: "change" }
  ]
});
// 进入详情进行判断节点位置
if (props.nodeDefId) {
  currentStep.value = ProcessStatusEnum[props.nodeDefId as string];
}

// 基础信息获取
const getInitFlowInfo = async () => {
  const { contractId } = props;
  if (!contractId) {
    return;
  }
  const params = {
    id: contractId
  };
  const { code, data } = await checkRecordInfo(params);
  if (code === 200) {
    formBaseInfo.value = data;
    isChargehand.value = formBaseInfo.value.isChargehand;
    taskIdMain.value = data.taskId;
    nextJumpToArr.value = flowTypeObj[flowType.value]?.nextJumpToArr || [];
    currentNode.value = flowTypeObj[flowType.value]?.curNodeName || ""; //某一节点的下一流程节点可选
    if (nextJumpToArr.value && nextJumpToArr.value.length) {
      nextJumpToId.value = nextJumpToArr.value[0].id;
      isChargehand.value = nextJumpToArr.value[0].isChargehand;
    }
    let nodeName = flowTypeObj[flowType.value].nodeName;
    nodeName.forEach(item => {
      steps.value.push({ step: item, title: item });
    });
    instanceIdFlow.value = data.instanceId;
    // flowFormData.value.approvalForm = approvals?.approvalForm;
    // flowFormData.value.defaultFileList = onInitFileList(
    //   data.formBaseInfo.flowStartAttachmentArr
    // );
    // props.isEdit && props.instanceId && getStorageTmpData();
  }
};

const handleRemove = (file, fileList) => {
  flowFormData.value.defaultFileList = fileList;
};

const handleChange = (file, fileList) => {
  flowFormData.value.defaultFileList = fileList;
  flowFormRef.value.clearValidate("defaultFileList");
};

const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return;
  const newFileData = list.map(item => {
    // if (item.status === "success") {
    return item.response.data;
    // }
  });
  return newFileData;
};

// const onInitFileList = (list: any[]) => {
//   if (!list || !list.length || !list[0]?.fileName) return;
//   const newFileList = list.map(item => {
//     return {
//       name: item?.fileName,
//       response: {
//         data: item,
//         code: 200
//       }
//     };
//   });
//   return newFileList;
// };

// 提交 saveState = 1
const handleSubmit = async () => {
  // 最后一个节点不需要选择下一节点处理人,直接取当前登录人
  const isValid = await new Promise(resolve =>
    flowFormRef.value.validate(resolve)
  );
  if (!isValid) return;
  let nodes = flowTypeObj[flowType.value].nodeId;
  if (props.nodeDefId === nodes[nodes.length - 1]) {
    emitAddUser();
  } else {
    dialogVisibleTransferAdd.value = true;
    dialogVisibleType.value = "submit";
  }
};

const showNextJump = parmas => {
  addUserInfo.value = parmas;
  if (dialogVisibleType.value === "submit") {
    //审核通过
    if (currentNode.value === props.nodeDefId) {
      //当前节点的下一步节点是可选的
      dialogVisibleTransferAdd.value = false;
      dialogVisibleNext.value = true;
    } else {
      emitAddUser();
    }
  }
};

const handleNextJump = () => {
  dialogVisibleNext.value = false;
  emitAddUser();
};

const emitAddUser = () => {
  dialogVisibleTransferAdd.value = false;
  const { instanceId } = props;
  let baseInfo = {
    billName: formBaseInfo.value.billName,
    projectName: formBaseInfo.value.projectName,
    projectManageId: formBaseInfo.value.projectManageId,
    contractName: formBaseInfo.value.contractName,
    contractId: formBaseInfo.value.contractId,
    contractNum: formBaseInfo.value.contractNum,
    partyA: formBaseInfo.value.partyA,
    directorAName: formBaseInfo.value.directorAName,
    directorA: formBaseInfo.value.directorA,
    directorBId: formBaseInfo.value.directorBId,
    partyB: formBaseInfo.value.partyB,
    directorBName: formBaseInfo.value.directorBName,
    id: formBaseInfo.value.id
  };

  let formData = {
    approvalComments: flowFormData.value.approvalComments,
    approvalForm: flowFormData.value.approvalForm,
    templateAttachment: onFilterFileData(flowFormData.value.defaultFileList)
  };
  instanceId && toSubmit(baseInfo, formData);
};

// 审批
const toSubmit = async (baseInfo, formData) => {
  const { nodeDefId, instanceId, flowId } = props;
  const info = storageLocal.getItem("info");
  let nodes = flowTypeObj[flowType.value].nodeId;
  //最后一个节点的下一步处理人为当前操作人
  let nextHandleId =
    props.nodeDefId === nodes[nodes.length - 1]
      ? info?.userId
      : addUserInfo.value?.idList[0]?.id;
  let params = {
    formBaseInfo: {
      id: formBaseInfo.value.id,
      acceptUsers: nextHandleId
    },
    flowFormData: {
      approvalResult: "1",
      businessId: formBaseInfo.value.id,
      flowId: flowId,
      flowTypeCode: flowType.value,
      instanceId: instanceId,
      nodeId: nodeDefId,
      projectManageId: storageLocal.getItem("projectInfo")?.id
    },
    formSubMap: {
      flowType: flowType.value,
      nodeId: nodeDefId,
      procInstId: instanceId,
      taskId: taskIdMain.value,
      opinion: `整改意见:${
        formData.approvalComments
      }#e#整改照片:${JSON.stringify(formData.templateAttachment)}`,
      assignee: nextHandleId,
      isChargehand: isChargehand.value || "0"
    },
    tmpStorage: {
      nodeId: nodeDefId,
      flowId,
      taskId: taskIdMain.value,
      handlerId: nextHandleId,
      userId: info ? info?.userId : "",
      valueJson: ""
    }
  };
  try {
    const { code, message } = await flowSubmit(params);
    if (code === 200) {
      NotifMessage.success(message);
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

//选择下一步流程节点
const changeNextJump = async id => {
  nextJumpToArr.value.forEach(item => {
    if (item.id === id) {
      formBaseInfo.value.isChargehand = item.isChargehand;
      isChargehand.value = item.isChargehand;
    }
  });
};

// 返回按钮事件
const handleBack = () => {
  router.push("/approval/todo");
};

const handleReject = () => {
  dialogVisible.value = true;
};

getInitFlowInfo();
defineExpose({ getInitFlowInfo, isChargehand });
// });
</script>

<style lang="scss" scoped>
.content-detail :deep .el-dialog .form__footer {
  text-align: right;
}
.next-content {
  padding: 10px 20px;
}
</style>
